package com.gopay.bis.service.bank.impl.ebank;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.ebank.CuccPayManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.CuccPayConstants;
import com.gopay.common.constants.bank.CuccPayOrderStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cuccpay.ebank.CuccPayMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.MoneyUtil;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 联通沃业务实现
 * 
 * CuccPayBankServiceImpl.java
 * @author WangHongFei
 */
public class CuccPayBankServiceImpl implements BankInteractRemoteService {
	
	@Resource(name = "cuccPayManager")
	CuccPayManager cuccPayManager;
	
	@Override
	public Result pay(BaseMessage base) {
		Result result = new Result(false);
		CuccPayMessage message = new CuccPayMessage();
		BeanUtils.copyProperties(base, message);
		try{
			message = (CuccPayMessage)cuccPayManager.sign(message);
	        result.setDefaultModel(message);
	        result.setSuccess(true);	
		}catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
		}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
		}
        return result;
	}

	@Override
	public Result bankBack(BaseMessage base) {
		Result result = new Result(false);
		CuccPayMessage message = new CuccPayMessage();
		BeanUtils.copyProperties(base, message);
		try{
			boolean flag = (Boolean)cuccPayManager.verify(message);
            result.setDefaultModel(flag);
            result.setModel("res", message);
            result.setSuccess(true);
			// 验签成功
            if (result != null && result.isSuccess() && (Boolean) result.getDefaultModel() && !base.isFront()) {
            	String amount = base.getAmount().toString();
            	amount = MoneyUtil.formatAmt(amount);
            	Map<String, String> param = new HashMap<String, String>();
            	// 如果该订单成功通知后台地址入账
            	if(message.getTransRst()!=null && message.getTransRst().equals("1")){
                    param.put("orderId", base.getOrderId());
                    param.put("amt", amount);
                    param.put("cardType", "Unknown");
                    param.put("notifyNum", "1");
                    param.put("payStatus", "00");
                    param.put("retCode", "00");
                    param.put("retMsg", message.getErrDis());
                    param.put("signData", message.getSignMsg());
                    param.put("isFront", String.valueOf(base.isFront()));
                    result.setModel("isNotifyCashier", param);
                    result.setOrderStatus(true);
            	}else{
                    // 通知后台地址该订单失败
                    param.put("orderId", base.getOrderId());
                    param.put("amt", amount);
                    param.put("cardType", "Unknown");
                    param.put("notifyNum", "1");
                    param.put("payStatus", "01");
                    param.put("retCode", "01");
                    param.put("retMsg", message.getErrDis());
                    param.put("signData", message.getSignMsg());
                    param.put("isFront", String.valueOf(base.isFront()));
                    result.setModel("isNotifyCashier", param);
                    result.setOrderStatus(false);
            	}
            }
    	}catch(GopayException e){
    		BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
    	}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		 return result;
	}

	@Override
	public Result query(BaseMessage base) {
		Result result = new Result(false);
		CuccPayMessage message = new CuccPayMessage();
		BeanUtils.copyProperties(base, message);
		try{
			message = (CuccPayMessage)cuccPayManager.query(message);
            result.setDefaultModel(message);
            result.setSuccess(true);
            if(BisPayCheckUtils.checkExternalOrderID(base.getOrderId())){
        		Map<String, String> param = new HashMap<String, String>();
        		String amount = base.getAmount().toString();
            	amount = MoneyUtil.formatAmt(amount);
        		param.put("orderId", base.getOrderId());
        		param.put("amount", amount);
        		if (message == null) {
                    // 查询订单为空
        			param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
        			param.put("returnMessage", "银行返回对账结果为空");
        			param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
                }

                if (!StringUtils.equals(CuccPayConstants.TRADE_RETURN_SUCCESS, message.getQueryResult())) {
                    // 查询订单错误
        			param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
        			param.put("returnMessage", "银行返回对账结果为空");
        			param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
                }
                //成功处理
                if (StringUtils.equals(CuccPayConstants.ORDER_STATE_SUCCESS, message.getOrderState())) {
    				param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
					param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
					param.put("returnMessage", "交易成功");
                } 
              //失败处理
                else if(StringUtils.equals(CuccPayConstants.ORDER_STATE_CLOSED, message.getOrderState())){   
    				param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);   	        	
					param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
					param.put("returnMessage", "交易失败");
                }
                else { 
    				param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);   
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    String errMsg = CuccPayOrderStatus.getName(message.getOrderState());
                    if (errMsg != null) {
    					param.put("returnMessage", errMsg);	        
                    } else {
    					param.put("returnMessage", "银行返回订单未查到");	  
                    }

                }
        		result.setModel("queryResult", param);
        	}
		}catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
		}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
		}
		 return result;
	}

	@Override
	public Result refund(BaseMessage base) {
		return null;
	}

	@Override
	public Result dayend(BaseMessage base) {
		return null;
	}

	@Override
	public Result queryBack(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public Result refundBack(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundQuery(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public Result sendBankRefund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

}
